"""
提示词模板管理API接口
提供提示词模板的CRUD操作、渲染、统计等功能
"""
from typing import List, Optional, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, Query, Body
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field
from datetime import datetime

from core.database import get_db
from core.auth import get_current_active_user
from core.exceptions import ValidationError
from services.prompt_template_service import PromptTemplateService
from services.prompt_renderer import prompt_renderer, RenderContext
from models.prompt_template import ParameterType, OutputFormat
from models.user import User

router = APIRouter()


# Pydantic模型
class ParameterDefinition(BaseModel):
    """参数定义模型"""
    name: str = Field(..., description="参数名称")
    description: Optional[str] = Field(None, description="参数描述")
    param_type: ParameterType = Field(default=ParameterType.STRING, description="参数类型")
    field_path: Optional[str] = Field(None, description="数据字段路径")
    is_required: bool = Field(default=False, description="是否必填")
    default_value: Optional[str] = Field(None, description="默认值")
    enum_values: Optional[List[str]] = Field(None, description="枚举值列表")
    min_length: Optional[int] = Field(None, description="最小长度")
    max_length: Optional[int] = Field(None, description="最大长度")
    min_value: Optional[int] = Field(None, description="最小值")
    max_value: Optional[int] = Field(None, description="最大值")
    pattern: Optional[str] = Field(None, description="正则表达式模式")
    display_name: Optional[str] = Field(None, description="显示名称")
    placeholder: Optional[str] = Field(None, description="占位符文本")
    help_text: Optional[str] = Field(None, description="帮助文本")
    ui_component: str = Field(default="input", description="UI组件类型")
    enable_thinking: bool = Field(default=False, description="是否在深度思考中使用")
    sort_order: int = Field(default=0, description="排序顺序")


class PromptTemplateCreate(BaseModel):
    """创建提示词模板请求模型"""
    name: str = Field(..., description="提示词名称")
    content: str = Field(..., description="提示词内容")
    description: Optional[str] = Field(None, description="提示词描述")
    category: Optional[str] = Field(None, description="提示词分类")
    service_type: Optional[str] = Field(None, description="关联的服务类型")
    service_id: Optional[str] = Field(None, description="关联的服务ID")
    output_format: OutputFormat = Field(default=OutputFormat.JSON, description="输出格式")
    tags: Optional[List[str]] = Field(None, description="标签列表")
    parameters: Optional[List[ParameterDefinition]] = Field(None, description="参数定义列表")
    is_system: bool = Field(default=False, description="是否系统模板")
    enable_thinking: bool = Field(default=False, description="是否启用深度思考")


class PromptTemplateUpdate(BaseModel):
    """更新提示词模板请求模型"""
    name: Optional[str] = Field(None, description="提示词名称")
    content: Optional[str] = Field(None, description="提示词内容")
    description: Optional[str] = Field(None, description="提示词描述")
    category: Optional[str] = Field(None, description="提示词分类")
    service_type: Optional[str] = Field(None, description="关联的服务类型")
    service_id: Optional[str] = Field(None, description="关联的服务ID")
    output_format: Optional[OutputFormat] = Field(None, description="输出格式")
    tags: Optional[List[str]] = Field(None, description="标签列表")
    is_active: Optional[bool] = Field(None, description="是否激活")


class RenderPromptRequest(BaseModel):
    """渲染提示词请求模型"""
    template_id: int = Field(..., description="模板ID")
    parameters: Dict[str, Any] = Field(..., description="参数值")
    session_id: Optional[str] = Field(None, description="会话ID")
    metadata: Optional[Dict[str, Any]] = Field(None, description="元数据")
    enable_thinking: Optional[bool] = Field(None, description="是否启用深度思考")


class ValidateTemplateRequest(BaseModel):
    """验证模板请求模型"""
    content: str = Field(..., description="模板内容")
    parameters: Optional[List[ParameterDefinition]] = Field(None, description="参数定义列表")


class BatchRenderRequest(BaseModel):
    """批量渲染请求模型"""
    template_id: int = Field(..., description="模板ID")
    batch_parameters: List[Dict[str, Any]] = Field(..., description="批量参数列表")


# API接口
@router.post("/", response_model=Dict[str, Any])
async def create_template(
    template_data: PromptTemplateCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建提示词模板"""
    
    service = PromptTemplateService(db)
    
    try:
        # 转换参数格式
        parameters = None
        if template_data.parameters:
            parameters = [param.dict() for param in template_data.parameters]
        
        template = service.create_template(
            name=template_data.name,
            content=template_data.content,
            description=template_data.description,
            category=template_data.category,
            service_type=template_data.service_type,
            service_id=template_data.service_id,
            output_format=template_data.output_format,
            tags=template_data.tags,
            parameters=parameters,
            is_system=template_data.is_system,
            enable_thinking=template_data.enable_thinking,
            created_by=current_user.id
        )
        
        return {
            "code": 200,
            "message": "创建成功",
            "data": template.to_dict()
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/", response_model=Dict[str, Any])
async def get_templates(
    category: Optional[str] = Query(None, description="分类筛选"),
    service_type: Optional[str] = Query(None, description="服务类型筛选"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    is_active: bool = Query(True, description="是否激活"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取提示词模板列表"""
    
    service = PromptTemplateService(db)
    
    try:
        result = service.get_templates(
            category=category,
            service_type=service_type,
            search=search,
            is_active=is_active,
            page=page,
            page_size=page_size
        )
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": result
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/{template_id}", response_model=Dict[str, Any])
async def get_template(
    template_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取提示词模板详情"""
    
    service = PromptTemplateService(db)
    
    try:
        template = service.get_template_by_id(template_id)
        return {
            "code": 200,
            "message": "获取成功",
            "data": template.to_dict()
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/{template_id}", response_model=Dict[str, Any])
async def update_template(
    template_id: int,
    template_data: PromptTemplateUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新提示词模板"""
    
    service = PromptTemplateService(db)
    
    try:
        # 转换参数格式
        update_data = template_data.dict(exclude_unset=True)
        
        template = service.update_template(template_id, **update_data)
        
        return {
            "code": 200,
            "message": "更新成功",
            "data": template.to_dict()
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/{template_id}", response_model=Dict[str, Any])
async def delete_template(
    template_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除提示词模板"""
    
    service = PromptTemplateService(db)
    
    try:
        success = service.delete_template(template_id)
        
        return {
            "code": 200,
            "message": "删除成功",
            "data": {"success": success}
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/render", response_model=Dict[str, Any])
async def render_prompt(
    render_request: RenderPromptRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """渲染提示词"""
    
    service = PromptTemplateService(db)
    
    try:
        # 获取模板详情
        template = service.get_template_by_id(render_request.template_id)
        
        # 获取参数定义
        parameter_definitions = [param.to_dict() for param in template.parameters]
        
        # 创建渲染上下文
        context = RenderContext(
            template_id=render_request.template_id,
            template_name=template.name,
            parameters=render_request.parameters,
            user_id=current_user.id,
            session_id=render_request.session_id,
            metadata=render_request.metadata or {}
        )
        
        # 使用服务层渲染，支持深度思考
        render_result = service.render_template(
            template_id=render_request.template_id,
            parameters=render_request.parameters,
            user_id=current_user.id,
            enable_thinking=render_request.enable_thinking
        )
        
        return {
            "code": 200,
            "message": "渲染成功",
            "data": {
                "rendered_prompt": render_result["rendered_prompt"],
                "thinking_content": render_result.get("thinking_content", ""),
                "parameters_used": render_result["parameters"],
                "output_format": render_result["output_format"],
                "render_time": render_result["render_time"],
                "enable_thinking": render_result.get("enable_thinking", False),
                "template_info": {
                    "id": template.id,
                    "name": template.name,
                    "output_format": template.output_format,
                    "enable_thinking": template.enable_thinking,
                }
            }
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/batch-render", response_model=Dict[str, Any])
async def batch_render_prompts(
    batch_request: BatchRenderRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量渲染提示词"""
    
    service = PromptTemplateService(db)
    
    try:
        # 获取模板详情
        template = service.get_template_by_id(batch_request.template_id)
        
        # 获取参数定义
        parameter_definitions = [param.to_dict() for param in template.parameters]
        
        # 批量渲染
        results = []
        for i, parameters in enumerate(batch_request.batch_parameters):
            try:
                context = RenderContext(
                    template_id=batch_request.template_id,
                    template_name=template.name,
                    parameters=parameters,
                    user_id=current_user.id,
                    session_id=f"batch_{i}"
                )
                
                result = prompt_renderer.render(
                    template_content=template.content,
                    parameters=parameters,
                    parameter_definitions=parameter_definitions,
                    context=context
                )
                
                results.append({
                    "index": i,
                    "success": True,
                    "rendered_prompt": result.rendered_prompt,
                    "validation_errors": result.validation_errors,
                    "render_time": result.render_time
                })
                
            except Exception as e:
                results.append({
                    "index": i,
                    "success": False,
                    "error": str(e)
                })
        
        return {
            "code": 200,
            "message": "批量渲染完成",
            "data": {
                "total_count": len(batch_request.batch_parameters),
                "success_count": len([r for r in results if r["success"]]),
                "results": results
            }
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/validate", response_model=Dict[str, Any])
async def validate_template(
    validate_request: ValidateTemplateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """验证提示词模板"""
    
    try:
        # 转换参数格式
        parameter_definitions = None
        if validate_request.parameters:
            parameter_definitions = [param.dict() for param in validate_request.parameters]
        
        # 验证模板
        result = prompt_renderer.validate_template(
            template_content=validate_request.content,
            parameter_definitions=parameter_definitions
        )
        
        return {
            "code": 200,
            "message": "验证完成",
            "data": result
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/templates/{template_id}/parameters", response_model=Dict[str, Any])
async def get_template_parameters(
    template_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取模板参数列表"""
    
    service = PromptTemplateService(db)
    
    try:
        template = service.get_template_by_id(template_id)
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "template_id": template_id,
                "parameters": [param.to_dict() for param in template.parameters]
            }
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/templates/{template_id}/parameters", response_model=Dict[str, Any])
async def add_template_parameter(
    template_id: int,
    parameter_data: ParameterDefinition,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """添加模板参数"""
    
    service = PromptTemplateService(db)
    
    try:
        parameter = service.add_parameter(
            template_id=template_id,
            param_data=parameter_data.dict()
        )
        
        return {
            "code": 200,
            "message": "添加成功",
            "data": parameter.to_dict()
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/parameters/{parameter_id}", response_model=Dict[str, Any])
async def update_template_parameter(
    parameter_id: int,
    parameter_data: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新模板参数"""
    
    service = PromptTemplateService(db)
    
    try:
        parameter = service.update_parameter(parameter_id, **parameter_data)
        
        return {
            "code": 200,
            "message": "更新成功",
            "data": parameter.to_dict()
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/parameters/{parameter_id}", response_model=Dict[str, Any])
async def delete_template_parameter(
    parameter_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除模板参数"""
    
    service = PromptTemplateService(db)
    
    try:
        success = service.delete_parameter(parameter_id)
        
        return {
            "code": 200,
            "message": "删除成功",
            "data": {"success": success}
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/templates/{template_id}/statistics", response_model=Dict[str, Any])
async def get_template_statistics(
    template_id: int,
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取模板使用统计"""
    
    service = PromptTemplateService(db)
    
    try:
        statistics = service.get_usage_statistics(
            template_id=template_id,
            start_date=start_date,
            end_date=end_date
        )
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": statistics
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/templates/{template_id}/duplicate", response_model=Dict[str, Any])
async def duplicate_template(
    template_id: int,
    new_name: str = Body(..., description="新模板名称"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """复制模板"""
    
    service = PromptTemplateService(db)
    
    try:
        new_template = service.duplicate_template(template_id, new_name)
        
        return {
            "code": 200,
            "message": "复制成功",
            "data": new_template.to_dict()
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/templates/{template_id}/example", response_model=Dict[str, Any])
async def get_template_example(
    template_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取模板示例用法"""
    
    service = PromptTemplateService(db)
    
    try:
        template = service.get_template_by_id(template_id)
        
        # 获取参数定义
        parameter_definitions = [param.to_dict() for param in template.parameters]
        
        # 生成示例
        example = prompt_renderer.generate_example_usage(
            template_content=template.content,
            parameter_definitions=parameter_definitions
        )
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": example
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/categories", response_model=Dict[str, Any])
async def get_template_categories(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取模板分类列表"""
    
    try:
        from models.prompt_template import PromptCategory
        categories = db.query(PromptCategory).filter(
            PromptCategory.is_active == True
        ).order_by(PromptCategory.sort_order).all()
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": [category.to_dict() for category in categories]
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))